package net.homeip.jcperera.webinfo.beans;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;

import net.homeip.jcperera.nu.core.boot.Boot;
import net.homeip.jcperera.nu.core.msg.BaseMessage;
import net.homeip.jcperera.nu.core.msg.MessageBagRequest;
import net.homeip.jcperera.webinfo.WebInfoPattern;
import net.homeip.jcperera.webinfo.WebInfoValue;

import org.primefaces.event.SelectEvent;

@ManagedBean
@ViewScoped
public class WebInfoValueBean implements Serializable
{
    private static final long serialVersionUID = 8776033011556276128L;

    private WebInfoValue      webInfoValue;

    public WebInfoValueBean()
    {
        webInfoValue = new WebInfoValue();
    }

    public List<WebInfoValue> getWebInfoValues()
    {
        List<WebInfoValue> webInfoValues = new ArrayList<WebInfoValue>();
        if (webInfoValue != null && webInfoValue.getPattern() != null)
        {
            webInfoValues.addAll(webInfoValue.getPattern().getWebinfovalues());
        }
        return webInfoValues;
    }

    public void saveWebInfoValue(ActionEvent actionEvent)
    {
        saveWebInfoValue();
    }

    public String saveWebInfoValue()
    {
        if (webInfoValue != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            if (webInfoValue.getEntityid() != null && webInfoValue.getEntityid().length() > 0)
                webInfoValue = entityManager.merge(webInfoValue);
            entityManager.persist(webInfoValue);
            entityManager.getTransaction().commit();
            entityManager.getEntityManagerFactory().getCache().evictAll();
            entityManager.close();
            MessageBagRequest messageBagRequest = new MessageBagRequest();
            messageBagRequest.addInformationalMessage("nu.core.entity.saved.ok", BaseMessage.FRIENDLINESS_FRIENDLY);
            messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
        }
        return "edit.xhtml?faces-redirect=true&entityid=" + this.getEntityid();
    }

    public void deleteWebInfoValue(ActionEvent actionEvent)
    {
        deleteWebInfoValue();
    }

    public String deleteWebInfoValue()
    {
        if (webInfoValue != null)
        {
            MessageBagRequest messageBagRequest = new MessageBagRequest();
            String entityid = webInfoValue.getEntityid();
            if (entityid != null && entityid.trim().length() > 0)
            {
                EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
                EntityManager entityManager = (EntityManager) emf.createEntityManager();
                entityManager.getTransaction().begin();
                webInfoValue = entityManager.merge(webInfoValue);
                entityManager.remove(webInfoValue);
                messageBagRequest.addInformationalMessage("nu.core.entity.deleted.ok",
                        BaseMessage.FRIENDLINESS_FRIENDLY);
                entityManager.getTransaction().commit();
                entityManager.getEntityManagerFactory().getCache().evictAll();
                entityManager.close();
            }
            messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
        }
        return "/pages/webinfopattern/edit.xhtml?faces-redirect=true&entityid=" + this.getParentid();
    }

    public String getEntityid()
    {
        return webInfoValue.getEntityid();
    }

    public void setEntityid(String entityid)
    {
        MessageBagRequest messageBagRequest = new MessageBagRequest();
        if (entityid != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            WebInfoValue webInfoValue = null;
            TypedQuery<WebInfoValue> wisQuery = entityManager.createQuery(
                    "SELECT OBJECT(wiv) FROM WebInfoValue wiv WHERE wiv.entityid = :entityid", WebInfoValue.class);
            wisQuery.setParameter("entityid", entityid);
            webInfoValue = wisQuery.getSingleResult();
            if (webInfoValue == null)
            {
                Hashtable<String, String> extensions = new Hashtable<String, String>();
                extensions.put("id", entityid);
                extensions.put("description", "Entity not found on database");
                messageBagRequest.addErrorMessage("nu.core.entity.type.load.error", BaseMessage.FRIENDLINESS_FRIENDLY,
                        extensions);
            }
            else this.webInfoValue = webInfoValue;
            entityManager.getTransaction().commit();
            entityManager.close();
        }
        messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
    }

    public String getParentid()
    {
        return ((webInfoValue != null && webInfoValue.getPattern() != null) ? webInfoValue.getPattern().getEntityid()
                : null);
    }

    public void setParentid(String entityid)
    {
        MessageBagRequest messageBagRequest = new MessageBagRequest();
        if (entityid != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            WebInfoPattern webInfoPattern = null;
            TypedQuery<WebInfoPattern> wisQuery = entityManager.createQuery(
                    "SELECT OBJECT(wip) FROM WebInfoPattern wip WHERE wip.entityid = :entityid", WebInfoPattern.class);
            wisQuery.setParameter("entityid", entityid);
            webInfoPattern = wisQuery.getSingleResult();
            if (webInfoPattern == null)
            {
                Hashtable<String, String> extensions = new Hashtable<String, String>();
                extensions.put("id", entityid);
                extensions.put("description", "Entity not found on database");
                messageBagRequest.addErrorMessage("nu.core.entity.type.load.error", BaseMessage.FRIENDLINESS_FRIENDLY,
                        extensions);
            }
            else this.webInfoValue.setPattern(webInfoPattern);
            entityManager.getTransaction().commit();
            entityManager.close();
        }
        messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
    }

    public void onRowSelect(SelectEvent event)
    {
        try
        {
            FacesContext.getCurrentInstance().getExternalContext()
                    .redirect("../webinfovalue/edit.xhtml?entityid=" + webInfoValue.getEntityid());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public WebInfoPattern getPattern()
    {
        return webInfoValue.getPattern();
    }

    public Boolean getFollowUpEnabled()
    {
        return webInfoValue.getFollowUpEnabled();
    }

    public void setFollowUpEnabled(Boolean followUpEnabled)
    {
        webInfoValue.setFollowUpEnabled(followUpEnabled);
    }

    public String getMatchingRegex()
    {
        return webInfoValue.getMatchingRegex();
    }

    public void setMatchingRegex(String matchingRegex)
    {
        webInfoValue.setMatchingRegex(matchingRegex);
    }

    public Boolean getPendingCheck()
    {
        return webInfoValue.getPendingCheck();
    }

    public void setPendingCheck(Boolean pendingCheck)
    {
        webInfoValue.setPendingCheck(pendingCheck);
    }

    public String getCreatedBy()
    {
        return webInfoValue.getCreatedBy();
    }

    public Date getCreatedWhen()
    {
        return webInfoValue.getCreatedWhen().getTime();
    }

    public String getModifiedBy()
    {
        return webInfoValue.getModifiedBy();
    }

    public Date getMofifiedWhen()
    {
        return webInfoValue.getModifiedWhen().getTime();
    }

    public long getLocalVersion()
    {
        return webInfoValue.getLocalVersion();
    }

    public long getGlobalVersion()
    {
        return webInfoValue.getGlobalVersion();
    }

    public void setSelectedWebInfoValue(WebInfoValue webInfoValue)
    {
        this.webInfoValue = webInfoValue;
    }

    public WebInfoValue getSelectedWebInfoValue()
    {
        return this.webInfoValue;
    }
}
